<template>
  <div class="withdrawal-page">
    <h1 class="page-title">佣金提现</h1>

    <!-- 标签页切换 -->
    <div class="tabs-container">
      <div class="tab-header">
        <div
          class="tab-item"
          :class="{ 'active': activeTab === 'myWithdrawal' }"
          @click="activeTab = 'myWithdrawal'"
        >
          <i class="fas fa-wallet"></i> 我的提现
        </div>
        <div
          class="tab-item"
          :class="{ 'active': activeTab === 'distributorWithdrawal' }"
          @click="activeTab = 'distributorWithdrawal'"
        >
          <i class="fas fa-users"></i> 经销商提现审核
        </div>
      </div>

      <!-- 我的提现内容 -->
      <div v-show="activeTab === 'myWithdrawal'" class="tab-content">
        <!-- 提现概览卡片 -->
        <div class="overview-cards">
          <div class="overview-card">
            <div class="overview-icon green">
              <i class="fas fa-wallet"></i>
            </div>
            <div class="overview-content">
              <div class="overview-title">可提现金额</div>
              <div class="overview-value">¥{{ formatNumber(withdrawalData.availableAmount) }}</div>
              <div class="overview-desc">满100元可提现</div>
            </div>
          </div>

          <div class="overview-card">
            <div class="overview-icon blue">
              <i class="fas fa-hourglass-half"></i>
            </div>
            <div class="overview-content">
              <div class="overview-title">提现中金额</div>
              <div class="overview-value">¥{{ formatNumber(withdrawalData.pendingAmount) }}</div>
              <div class="overview-desc">审核中的提现申请</div>
            </div>
          </div>

          <div class="overview-card">
            <div class="overview-icon purple">
              <i class="fas fa-check-circle"></i>
            </div>
            <div class="overview-content">
              <div class="overview-title">已提现总额</div>
              <div class="overview-value">¥{{ formatNumber(withdrawalData.totalWithdrawn) }}</div>
              <div class="overview-desc">累计已提现金额</div>
            </div>
          </div>

          <div class="overview-card">
            <div class="overview-content centered">
              <button class="btn-withdraw" @click="showWithdrawalForm = true">
                <i class="fas fa-money-bill-wave"></i> 申请提现
              </button>
            </div>
          </div>
        </div>

        <!-- 我的提现记录表格 -->
        <div class="withdrawal-table">
          <div class="table-header">
            <h2 class="section-title">我的提现记录</h2>
            <div class="filter-actions">
              <select v-model="filterStatus" class="status-filter">
                <option value="all">全部状态</option>
                <option value="pending">待审核</option>
                <option value="approved">已通过</option>
                <option value="rejected">已拒绝</option>
                <option value="paid">已打款</option>
              </select>
              <div class="date-range">
                <input type="date" v-model="filterStartDate" class="date-input" />
                <span class="date-separator">至</span>
                <input type="date" v-model="filterEndDate" class="date-input" />
                <button class="btn-filter" @click="applyFilters">筛选</button>
              </div>
            </div>
          </div>

          <div class="table-container">
            <table>
              <thead>
                <tr>
                  <th>申请订单号</th>
                  <th>申请时间</th>
                  <th>提现金额</th>
                  <th>USDT钱包地址</th>
                  <th>USDT网络</th>
                  <th>状态</th>
                  <th>审核时间</th>
                  <th>交易哈希</th>
                  <th>备注</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in myWithdrawalRecords" :key="item.id">
                  <td>{{ item.id }}</td>
                  <td>{{ formatDate(item.applyTime) }}</td>
                  <td class="amount">¥{{ formatNumber(item.amount) }}</td>
                  <td>{{ maskAddress(item.usdtAddress) }}</td>
                  <td>{{ item.usdtNetwork }}</td>
                  <td>
                    <span
                      class="status-badge"
                      :class="getStatusClass(item.status)"
                    >
                      {{ getStatusText(item.status) }}
                    </span>
                  </td>
                  <td>{{ item.reviewTime ? formatDate(item.reviewTime) : '-' }}</td>
                  <td>
                    <a v-if="item.txHash" :href="'https://tronscan.org/#/transaction/' + item.txHash" target="_blank" class="tx-hash">
                      {{ shortenHash(item.txHash) }}
                    </a>
                    <span v-else>-</span>
                  </td>
                  <td>{{ item.remark || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页 -->
          <div class="pagination">
            <a href="#" class="page-link" @click.prevent="changePage(myCurrentPage - 1, 'my')" :class="{ disabled: myCurrentPage === 1 }">&laquo;</a>
            <template v-for="n in myTotalPages" :key="n">
              <a
                href="#"
                class="page-link"
                :class="{ active: myCurrentPage === n }"
                @click.prevent="changePage(n, 'my')"
              >
                {{ n }}
              </a>
            </template>
            <a href="#" class="page-link" @click.prevent="changePage(myCurrentPage + 1, 'my')" :class="{ disabled: myCurrentPage === myTotalPages }">&raquo;</a>
          </div>
        </div>
      </div>

      <!-- 经销商提现审核内容 -->
      <div v-show="activeTab === 'distributorWithdrawal'" class="tab-content">
        <!-- 筛选区域 -->
        <div class="filter-section">
          <div class="search-box">
            <input
              type="text"
              v-model="distributorFilter.keyword"
              class="search-input"
              placeholder="搜索经销商名称或钱包地址"
            >
            <button class="search-btn"><i class="fas fa-search"></i></button>
          </div>

          <div class="filter-item">
            <div class="date-range">
              <input type="date" v-model="distributorFilter.startDate" class="date-input" />
              <span class="date-separator">至</span>
              <input type="date" v-model="distributorFilter.endDate" class="date-input" />
            </div>
          </div>

          <div class="filter-item">
            <select v-model="distributorFilter.status" class="status-filter">
              <option value="all">全部状态</option>
              <option value="pending">待审核</option>
              <option value="approved">已通过</option>
              <option value="rejected">已拒绝</option>
            </select>
          </div>

          <button class="btn-filter" @click="applyDistributorFilters">
            <i class="fas fa-filter"></i> 筛选
          </button>
        </div>

        <!-- 待审核提现申请统计卡片 -->
        <div class="alert-card" v-if="pendingReviewCount > 0">
          <div class="alert-icon">
            <i class="fas fa-exclamation-circle"></i>
          </div>
          <div class="alert-content">
            <div class="alert-title">有 {{ pendingReviewCount }} 条提现申请待审核</div>
            <div class="alert-desc">总金额: ¥{{ formatNumber(pendingReviewAmount) }}</div>
          </div>
          <button class="btn-review-all" @click="focusPendingReviews">
            立即审核 <i class="fas fa-arrow-right"></i>
          </button>
        </div>

        <!-- 经销商提现申请表格 -->
        <div class="withdrawal-table">
          <div class="table-header">
            <h2 class="section-title">经销商提现申请</h2>
          </div>

          <div class="table-container">
            <table>
              <thead>
                <tr>
                  <th>申请ID</th>
                  <th>申请时间</th>
                  <th>经销商</th>
                  <th>提现金额</th>
                  <th>USDT钱包地址</th>
                  <th>USDT网络</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in distributorWithdrawalRecords" :key="item.id">
                  <td>{{ item.id }}</td>
                  <td>{{ formatDate(item.applyTime) }}</td>
                  <td class="distributor-cell">
                    <img :src="item.distributorAvatar" alt="头像" class="distributor-avatar" />
                    <span>{{ item.distributorName }}</span>
                  </td>
                  <td class="amount">¥{{ formatNumber(item.amount) }}</td>
                  <td>{{ maskAddress(item.usdtAddress) }}</td>
                  <td>{{ item.usdtNetwork }}</td>
                  <td>
                    <span
                      class="status-badge"
                      :class="getStatusClass(item.status)"
                    >
                      {{ getStatusText(item.status) }}
                    </span>
                  </td>
                  <td class="actions-cell">
                    <button class="btn-action view" @click="openReviewModal(item)">
                      <i class="fas fa-eye"></i>
                    </button>
                    <button
                      v-if="item.status === 'pending'"
                      class="btn-action approve"
                      @click="quickReview(item, 'approved')"
                    >
                      <i class="fas fa-check"></i>
                    </button>
                    <button
                      v-if="item.status === 'pending'"
                      class="btn-action reject"
                      @click="quickReview(item, 'rejected')"
                    >
                      <i class="fas fa-times"></i>
                    </button>
                  </td>
                </tr>
                <tr v-if="distributorWithdrawalRecords.length === 0">
                  <td colspan="8" class="no-data">暂无提现申请记录</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页 -->
          <div class="pagination" v-if="distributorWithdrawalRecords.length > 0">
            <a href="#" class="page-link" @click.prevent="changePage(distributorCurrentPage - 1, 'distributor')" :class="{ disabled: distributorCurrentPage === 1 }">&laquo;</a>
            <template v-for="n in distributorTotalPages" :key="n">
              <a
                href="#"
                class="page-link"
                :class="{ active: distributorCurrentPage === n }"
                @click.prevent="changePage(n, 'distributor')"
              >
                {{ n }}
              </a>
            </template>
            <a href="#" class="page-link" @click.prevent="changePage(distributorCurrentPage + 1, 'distributor')" :class="{ disabled: distributorCurrentPage === distributorTotalPages }">&raquo;</a>
          </div>
        </div>
      </div>
    </div>

    <!-- 提现申请表单弹窗 -->
    <div class="modal" v-if="showWithdrawalForm">
      <div class="modal-overlay" @click="showWithdrawalForm = false"></div>
      <div class="modal-container">
        <div class="modal-header">
          <h3>申请提现</h3>
          <button class="btn-close" @click="showWithdrawalForm = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <form class="withdrawal-form" @submit.prevent="submitWithdrawal">
            <div class="form-group">
              <label for="amount">提现金额</label>
              <div class="input-wrapper">
                <input
                  type="number"
                  id="amount"
                  v-model="withdrawalForm.amount"
                  placeholder="请输入提现金额"
                  class="form-control"
                  :class="{ 'is-invalid': !isAmountValid && withdrawalForm.amount }"
                  step="0.01"
                  min="100"
                  :max="withdrawalData.availableAmount"
                  required
                />
                <div class="input-hint">可提现: ¥{{ formatNumber(withdrawalData.availableAmount) }}</div>
              </div>
              <div class="invalid-feedback" v-if="!isAmountValid && withdrawalForm.amount">
                提现金额必须在100-{{ formatNumber(withdrawalData.availableAmount) }}元之间
              </div>
            </div>

            <div class="form-group">
              <label for="paymentMethod">收款方式</label>
              <input
                type="text"
                id="paymentMethod"
                value="USDT"
                class="form-control"
                readonly
              />
            </div>

            <div class="form-group">
              <label for="usdtAddress">USDT钱包地址</label>
              <input
                type="text"
                id="usdtAddress"
                v-model="withdrawalForm.usdtAddress"
                placeholder="请输入您的USDT钱包地址"
                class="form-control"
                :class="{ 'is-invalid': !isUsdtAddressValid && withdrawalForm.usdtAddress }"
                required
              />
              <div class="invalid-feedback" v-if="!isUsdtAddressValid && withdrawalForm.usdtAddress">
                请输入有效的USDT钱包地址
              </div>
            </div>

            <div class="form-group">
              <label for="usdtNetwork">USDT网络</label>
              <select
                id="usdtNetwork"
                v-model="withdrawalForm.usdtNetwork"
                class="form-control"
                required
              >
                <option value="TRC20">TRC20 (推荐，手续费低)</option>
                <option value="ERC20">ERC20</option>
              </select>
            </div>

            <div class="form-group">
              <label for="remark">交易备注 (可选)</label>
              <textarea
                id="remark"
                v-model="withdrawalForm.remark"
                placeholder="可选填写备注信息"
                class="form-control"
                rows="2"
                maxlength="100"
              ></textarea>
              <div class="text-counter">{{ withdrawalForm.remark.length }}/100</div>
            </div>

            <div class="form-actions">
              <button type="button" class="btn-secondary" @click="showWithdrawalForm = false">取消</button>
              <button type="submit" class="btn-primary" :disabled="isSubmitting || !isFormValid">
                <span v-if="isSubmitting"><i class="fas fa-spinner fa-spin"></i> 提交中...</span>
                <span v-else>提交申请</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 审核操作模态框 -->
    <div class="modal" v-if="showReviewModal">
      <div class="modal-overlay" @click="closeReviewModal"></div>
      <div class="modal-container">
        <div class="modal-header">
          <h3>提现申请审核</h3>
          <button class="btn-close" @click="closeReviewModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="review-details">
            <div class="review-item">
              <div class="review-label">经销商</div>
              <div class="review-value distributor-detail" v-if="currentReviewItem">
                <img :src="currentReviewItem.distributorAvatar" alt="头像" class="distributor-avatar" />
                <span>{{ currentReviewItem.distributorName }}</span>
              </div>
            </div>

            <div class="review-item">
              <div class="review-label">申请ID</div>
              <div class="review-value" v-if="currentReviewItem">{{ currentReviewItem.id }}</div>
            </div>

            <div class="review-item">
              <div class="review-label">申请时间</div>
              <div class="review-value" v-if="currentReviewItem">{{ formatDate(currentReviewItem.applyTime) }}</div>
            </div>

            <div class="review-item">
              <div class="review-label">提现金额</div>
              <div class="review-value amount" v-if="currentReviewItem">¥{{ formatNumber(currentReviewItem.amount) }}</div>
            </div>

            <div class="review-item">
              <div class="review-label">USDT钱包地址</div>
              <div class="review-value address" v-if="currentReviewItem">{{ currentReviewItem.usdtAddress }}</div>
            </div>

            <div class="review-item">
              <div class="review-label">USDT网络</div>
              <div class="review-value" v-if="currentReviewItem">{{ currentReviewItem.usdtNetwork }}</div>
            </div>

            <div class="review-item">
              <div class="review-label">审核结果</div>
              <div class="review-value">
                <div class="review-options">
                  <div
                    class="review-option"
                    :class="{ active: reviewForm.result === 'approved' }"
                    @click="reviewForm.result = 'approved'"
                  >
                    <i class="fas fa-check-circle"></i> 通过
                  </div>
                  <div
                    class="review-option"
                    :class="{ active: reviewForm.result === 'rejected' }"
                    @click="reviewForm.result = 'rejected'"
                  >
                    <i class="fas fa-times-circle"></i> 拒绝
                  </div>
                </div>
              </div>
            </div>

            <div class="review-item" v-if="reviewForm.result === 'rejected'">
              <div class="review-label">拒绝原因</div>
              <div class="review-value">
                <select v-model="reviewForm.rejectReason" class="form-control">
                  <option value="地址错误">USDT地址格式错误</option>
                  <option value="余额不足">账户余额不足</option>
                  <option value="提现限制">不满足最低提现金额要求</option>
                  <option value="其他原因">其他原因</option>
                </select>
              </div>
            </div>

            <div class="review-item">
              <div class="review-label">审核备注 (可选)</div>
              <div class="review-value">
                <textarea
                  v-model="reviewForm.remark"
                  placeholder="可选填写审核备注信息"
                  class="form-control"
                  rows="2"
                  maxlength="100"
                ></textarea>
                <div class="text-counter">{{ reviewForm.remark.length }}/100</div>
              </div>
            </div>
          </div>

          <div class="form-actions">
            <button type="button" class="btn-secondary" @click="closeReviewModal">取消</button>
            <button
              type="button"
              class="btn-primary"
              :disabled="isSubmittingReview"
              @click="submitReview"
            >
              <span v-if="isSubmittingReview"><i class="fas fa-spinner fa-spin"></i> 提交中...</span>
              <span v-else>确认</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { showToast, showSuccessToast } from 'vant'

// 当前激活的标签页
const activeTab = ref('myWithdrawal') // 默认显示"我的提现"标签页

// 提现数据
const withdrawalData = reactive({
  availableAmount: 6850.25,
  pendingAmount: 1200.00,
  totalWithdrawn: 15680.50,
})

// 提现表单显示状态
const showWithdrawalForm = ref(false)
const isSubmitting = ref(false)

// 提现表单数据
const withdrawalForm = reactive({
  amount: '',
  usdtAddress: '',
  usdtNetwork: 'TRC20',
  remark: '',
})

// 表单验证
const isAmountValid = computed(() => {
  const amount = parseFloat(withdrawalForm.amount.toString())
  return !withdrawalForm.amount || (amount >= 100 && amount <= withdrawalData.availableAmount)
})

const isUsdtAddressValid = computed(() => {
  return !withdrawalForm.usdtAddress ||
    (withdrawalForm.usdtNetwork === 'TRC20' && /^T[a-zA-Z0-9]{33}$/.test(withdrawalForm.usdtAddress)) ||
    (withdrawalForm.usdtNetwork === 'ERC20' && /^0x[a-fA-F0-9]{40}$/.test(withdrawalForm.usdtAddress))
})

const isFormValid = computed(() => {
  return isAmountValid.value &&
    isUsdtAddressValid.value &&
    !!withdrawalForm.amount &&
    !!withdrawalForm.usdtAddress
})

// 我的提现记录筛选状态
const filterStatus = ref('all')
const filterStartDate = ref('')
const filterEndDate = ref('')
const myCurrentPage = ref(1)
const pageSize = ref(10)

// 模拟我的提现记录数据
const allMyWithdrawalRecords = ref([
  {
    id: 'WD20230601001',
    applyTime: '2023-06-01 14:30:25',
    amount: 1000.00,
    usdtAddress: 'TRWJkADmKNRSvQj1CQiTrGAbQSxCpVkwGx',
    usdtNetwork: 'TRC20',
    status: 'paid',
    reviewTime: '2023-06-02 10:15:30',
    txHash: '7f93d4cf2cba1d76cae0de829e41bd88407c577dd0bbe2c396c3f37c9fa53879',
    remark: '月度提现'
  },
  {
    id: 'WD20230615002',
    applyTime: '2023-06-15 09:22:18',
    amount: 2500.00,
    usdtAddress: 'TRWJkADmKNRSvQj1CQiTrGAbQSxCpVkwGx',
    usdtNetwork: 'TRC20',
    status: 'paid',
    reviewTime: '2023-06-16 11:05:42',
    txHash: '9e74e332f3c4c662f3b551f33d4a0a38b71d4981af834a6621a5ef8e5744633f',
    remark: ''
  },
  {
    id: 'WD20230702003',
    applyTime: '2023-07-02 16:45:33',
    amount: 1800.00,
    usdtAddress: 'TRWJkADmKNRSvQj1CQiTrGAbQSxCpVkwGx',
    usdtNetwork: 'TRC20',
    status: 'approved',
    reviewTime: '2023-07-03 14:20:15',
    txHash: '',
    remark: '周佣金提现'
  },
  {
    id: 'WD20230720004',
    applyTime: '2023-07-20 10:12:50',
    amount: 3200.00,
    usdtAddress: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
    usdtNetwork: 'ERC20',
    status: 'pending',
    reviewTime: null,
    txHash: '',
    remark: ''
  },
  {
    id: 'WD20230805005',
    applyTime: '2023-08-05 11:30:22',
    amount: 1500.00,
    usdtAddress: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
    usdtNetwork: 'ERC20',
    status: 'rejected',
    reviewTime: '2023-08-06 09:45:10',
    txHash: '',
    remark: 'USDT地址格式错误'
  },
  {
    id: 'WD20230818006',
    applyTime: '2023-08-18 15:10:05',
    amount: 2000.00,
    usdtAddress: 'TRWJkADmKNRSvQj1CQiTrGAbQSxCpVkwGx',
    usdtNetwork: 'TRC20',
    status: 'pending',
    reviewTime: null,
    txHash: '',
    remark: ''
  }
])

// 根据筛选条件计算显示的记录
const filteredMyWithdrawalRecords = computed(() => {
  let result = [...allMyWithdrawalRecords.value]

  // 应用状态筛选
  if (filterStatus.value !== 'all') {
    result = result.filter(record => record.status === filterStatus.value)
  }

  // 应用日期筛选
  if (filterStartDate.value) {
    const startDate = new Date(filterStartDate.value)
    result = result.filter(record => new Date(record.applyTime) >= startDate)
  }

  if (filterEndDate.value) {
    const endDate = new Date(filterEndDate.value)
    endDate.setHours(23, 59, 59, 999) // 设置为当天的最后一刻
    result = result.filter(record => new Date(record.applyTime) <= endDate)
  }

  return result
})

// 计算分页后的记录
const myWithdrawalRecords = computed(() => {
  const start = (myCurrentPage.value - 1) * pageSize.value
  return filteredMyWithdrawalRecords.value.slice(start, start + pageSize.value)
})

// 计算总页数
const myTotalPages = computed(() => {
  return Math.max(1, Math.ceil(filteredMyWithdrawalRecords.value.length / pageSize.value))
})

// 经销商提现记录相关
const distributorFilter = reactive({
  keyword: '',
  startDate: '',
  endDate: '',
  status: 'all'
})

const distributorCurrentPage = ref(1)

// 模拟经销商提现数据
const allDistributorWithdrawalRecords = ref([
  {
    id: 'WD20230610001',
    applyTime: '2023-06-10 09:15:20',
    distributorName: '张三',
    distributorAvatar: 'https://randomuser.me/api/portraits/men/1.jpg',
    amount: 1200.00,
    usdtAddress: 'TGjgvdTWWrybVLaVeFqSfNhEo1JEACLLs2',
    usdtNetwork: 'TRC20',
    status: 'pending',
    reviewTime: null,
    txHash: '',
    remark: ''
  },
  {
    id: 'WD20230615002',
    applyTime: '2023-06-15 14:30:45',
    distributorName: '李四',
    distributorAvatar: 'https://randomuser.me/api/portraits/men/2.jpg',
    amount: 2000.00,
    usdtAddress: 'TVuTV9bQYH5GgC3NzqUACbNE2yoKjwZFrq',
    usdtNetwork: 'TRC20',
    status: 'approved',
    reviewTime: '2023-06-16 10:20:15',
    txHash: '',
    remark: '已通过审核，等待打款'
  },
  {
    id: 'WD20230622003',
    applyTime: '2023-06-22 11:45:30',
    distributorName: '王五',
    distributorAvatar: 'https://randomuser.me/api/portraits/men/3.jpg',
    amount: 1500.00,
    usdtAddress: '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',
    usdtNetwork: 'ERC20',
    status: 'rejected',
    reviewTime: '2023-06-23 09:10:30',
    txHash: '',
    remark: 'ERC20地址格式有误'
  },
  {
    id: 'WD20230701004',
    applyTime: '2023-07-01 16:20:10',
    distributorName: '赵六',
    distributorAvatar: 'https://randomuser.me/api/portraits/men/4.jpg',
    amount: 3000.00,
    usdtAddress: 'TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL',
    usdtNetwork: 'TRC20',
    status: 'pending',
    reviewTime: null,
    txHash: '',
    remark: ''
  },
  {
    id: 'WD20230710005',
    applyTime: '2023-07-10 08:45:55',
    distributorName: '孙七',
    distributorAvatar: 'https://randomuser.me/api/portraits/men/5.jpg',
    amount: 2500.00,
    usdtAddress: 'TAKX5sJtU9UXXvoQHgpJWgeo6bGGa5FrQe',
    usdtNetwork: 'TRC20',
    status: 'approved',
    reviewTime: '2023-07-11 10:30:25',
    txHash: '',
    remark: ''
  }
])

// 根据筛选条件计算显示的经销商记录
const filteredDistributorWithdrawalRecords = computed(() => {
  let result = [...allDistributorWithdrawalRecords.value]

  // 应用关键词筛选
  if (distributorFilter.keyword) {
    const keyword = distributorFilter.keyword.toLowerCase()
    result = result.filter(record =>
      record.distributorName.toLowerCase().includes(keyword) ||
      record.usdtAddress.toLowerCase().includes(keyword)
    )
  }

  // 应用状态筛选
  if (distributorFilter.status !== 'all') {
    result = result.filter(record => record.status === distributorFilter.status)
  }

  // 应用日期筛选
  if (distributorFilter.startDate) {
    const startDate = new Date(distributorFilter.startDate)
    result = result.filter(record => new Date(record.applyTime) >= startDate)
  }

  if (distributorFilter.endDate) {
    const endDate = new Date(distributorFilter.endDate)
    endDate.setHours(23, 59, 59, 999)
    result = result.filter(record => new Date(record.applyTime) <= endDate)
  }

  return result
})

// 计算分页后的经销商记录
const distributorWithdrawalRecords = computed(() => {
  const start = (distributorCurrentPage.value - 1) * pageSize.value
  return filteredDistributorWithdrawalRecords.value.slice(start, start + pageSize.value)
})

// 计算待审核提现数量和金额
const pendingReviewCount = computed(() => {
  return allDistributorWithdrawalRecords.value.filter(
    record => record.status === 'pending'
  ).length
})

const pendingReviewAmount = computed(() => {
  return allDistributorWithdrawalRecords.value
    .filter(record => record.status === 'pending')
    .reduce((total, record) => total + record.amount, 0)
})

// 计算经销商记录总页数
const distributorTotalPages = computed(() => {
  return Math.max(1, Math.ceil(filteredDistributorWithdrawalRecords.value.length / pageSize.value))
})

// 审核相关
const showReviewModal = ref(false)
const isSubmittingReview = ref(false)
const currentReviewItem = ref(null)

const reviewForm = reactive({
  result: 'approved',
  rejectReason: '地址错误',
  remark: '',
})

// 打开审核模态框
const openReviewModal = (item) => {
  currentReviewItem.value = item
  reviewForm.result = 'approved'
  reviewForm.rejectReason = '地址错误'
  reviewForm.remark = ''
  showReviewModal.value = true
}

// 关闭审核模态框
const closeReviewModal = () => {
  showReviewModal.value = false
  currentReviewItem.value = null
}

// 快速审核方法
const quickReview = (item, result) => {
  currentReviewItem.value = item
  reviewForm.result = result
  reviewForm.remark = ''

  if (result === 'rejected') {
    openReviewModal(item)
  } else {
    submitReview()
  }
}

// 提交审核结果
const submitReview = () => {
  if (!currentReviewItem.value) return

  isSubmittingReview.value = true

  // 模拟API请求
  setTimeout(() => {
    // 更新记录状态
    const index = allDistributorWithdrawalRecords.value.findIndex(
      item => item.id === currentReviewItem.value.id
    )

    if (index !== -1) {
      allDistributorWithdrawalRecords.value[index] = {
        ...allDistributorWithdrawalRecords.value[index],
        status: reviewForm.result,
        reviewTime: new Date().toISOString(),
        remark: reviewForm.result === 'rejected'
          ? `${reviewForm.rejectReason}${reviewForm.remark ? ': ' + reviewForm.remark : ''}`
          : reviewForm.remark
      }
    }

    // 关闭模态框并显示成功提示
    showReviewModal.value = false
    isSubmittingReview.value = false
    currentReviewItem.value = null

    // 显示成功提示
    alert(`提现申请已${reviewForm.result === 'approved' ? '通过' : '拒绝'}`)
  }, 800)
}

// 专注于待审核
const focusPendingReviews = () => {
  distributorFilter.status = 'pending'
  applyDistributorFilters()
}

// 应用经销商筛选条件
const applyDistributorFilters = () => {
  distributorCurrentPage.value = 1
}

// 格式化金额，保留两位小数并添加千位分隔符
const formatNumber = (num: number): string => {
  return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 格式化日期
const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`
}

// 补零函数
const padZero = (num: number): string => {
  return num < 10 ? `0${num}` : num.toString()
}

// 获取状态对应的样式类
const getStatusClass = (status: string): string => {
  switch (status) {
    case 'pending': return 'status-pending'
    case 'approved': return 'status-approved'
    case 'rejected': return 'status-rejected'
    case 'paid': return 'status-paid'
    default: return ''
  }
}

// 获取状态对应的文本
const getStatusText = (status: string): string => {
  switch (status) {
    case 'pending': return '待审核'
    case 'approved': return '已通过'
    case 'rejected': return '已拒绝'
    case 'paid': return '已打款'
    default: return status
  }
}

// 掩码处理钱包地址
const maskAddress = (address: string): string => {
  if (!address) return '';
  if (address.length < 10) return address;

  return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
}

// 缩短交易哈希显示
const shortenHash = (hash: string): string => {
  if (!hash) return '';
  if (hash.length < 10) return hash;

  return `${hash.substring(0, 8)}...${hash.substring(hash.length - 6)}`;
}

// 切换页码
const changePage = (page: number, type: 'my' | 'distributor') => {
  if (type === 'my') {
    if (page < 1 || page > myTotalPages.value) return;
    myCurrentPage.value = page;
  } else {
    if (page < 1 || page > distributorTotalPages.value) return;
    distributorCurrentPage.value = page;
  }
}

// 应用筛选条件
const applyFilters = () => {
  myCurrentPage.value = 1; // 重置为第一页
}

// 提交提现申请
const submitWithdrawal = () => {
  if (!isFormValid.value) return;

  isSubmitting.value = true;

  // 模拟API请求延迟
  setTimeout(() => {
    // 生成新的提现记录
    const newRecord = {
      id: `WD${new Date().getTime().toString().slice(-8)}`,
      applyTime: new Date().toISOString(),
      amount: parseFloat(withdrawalForm.amount.toString()),
      usdtAddress: withdrawalForm.usdtAddress,
      usdtNetwork: withdrawalForm.usdtNetwork,
      status: 'pending',
      reviewTime: null,
      txHash: '',
      remark: withdrawalForm.remark || ''
    };

    // 添加到记录列表
    allMyWithdrawalRecords.value.unshift(newRecord);

    // 更新可提现金额和提现中金额
    const amount = parseFloat(withdrawalForm.amount.toString());
    withdrawalData.availableAmount -= amount;
    withdrawalData.pendingAmount += amount;

    // 重置表单
    withdrawalForm.amount = '';
    withdrawalForm.remark = '';

    // 关闭弹窗并显示成功提示
    showWithdrawalForm.value = false;
    isSubmitting.value = false;

    // 显示成功提示
    alert('提现申请已提交，等待审核');
  }, 1000);
}

onMounted(() => {
  // 加载数据...
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';

.withdrawal-page {
  padding: 20px;
}

.page-title {
  margin-top: 0;
  margin-bottom: 24px;
  color: $text-primary;
  font-size: 24px;
  font-weight: $font-weight-semibold;
  position: relative;

  &:after {
    content: '';
    position: absolute;
    left: 0;
    bottom: -8px;
    width: 40px;
    height: 3px;
    background: linear-gradient(90deg, $primary, $primary-light);
    border-radius: 3px;
  }
}

.tabs-container {
  background-color: white;
  border-radius: 12px;
  box-shadow: $shadow-sm;
  overflow: hidden;
  margin-bottom: 24px;
}

.tab-header {
  display: flex;
  border-bottom: 1px solid $gray-200;
}

.tab-item {
  padding: 16px 24px;
  font-weight: $font-weight-medium;
  color: $text-secondary;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  display: flex;
  align-items: center;

  i {
    margin-right: 8px;
  }

  &:hover {
    color: $primary;
  }

  &.active {
    color: $primary;

    &:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 3px;
      background-color: $primary;
    }
  }
}

.tab-content {
  padding: 24px;
}

// 提现概览卡片
.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.overview-card {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: $shadow-sm;
  transition: transform 0.2s, box-shadow 0.2s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: $shadow-md;
  }

  .overview-content.centered {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
  }
}

.overview-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;

  &.green {
    background-color: $success;
  }

  &.blue {
    background-color: $info;
  }

  &.purple {
    background-color: #8b5cf6;
  }
}

.overview-content {
  flex: 1;
}

.overview-title {
  font-size: 14px;
  color: $text-secondary;
  margin-bottom: 8px;
}

.overview-value {
  font-size: 24px;
  font-weight: $font-weight-semibold;
  color: $text-primary;
  margin-bottom: 5px;
}

.overview-desc {
  font-size: 13px;
  color: $text-secondary;
}

.btn-withdraw {
  width: 100%;
  height: 44px;
  background-color: $primary;
  color: white;
  border: none;
  border-radius: $border-radius-md;
  font-size: 16px;
  font-weight: $font-weight-medium;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;

  i {
    margin-right: 8px;
  }

  &:hover {
    background-color: $primary-dark;
  }
}

// 提现记录表格
.withdrawal-table {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: $shadow-sm;
}

.section-title {
  font-size: $font-size-lg;
  margin: 0;
  color: $text-primary;
  font-weight: $font-weight-semibold;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-filter {
  padding: 8px 12px;
  border: 1px solid $gray-300;
  border-radius: $border-radius-md;
  background-color: white;
  color: $text-primary;
  font-size: 14px;
  outline: none;
}

.date-range {
  display: flex;
  align-items: center;
}

.date-input {
  padding: 8px;
  border: 1px solid $gray-300;
  border-radius: $border-radius-md;
  width: 130px;
  font-size: 14px;
  color: $text-primary;
  outline: none;
}

.date-separator {
  margin: 0 8px;
  color: $text-secondary;
}

.btn-filter {
  background-color: $primary;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: $border-radius-md;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover {
    background-color: $primary-dark;
  }
}

.table-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid $gray-200;
}

th {
  font-weight: $font-weight-medium;
  color: $text-secondary;
  background-color: $gray-100;
}

td {
  color: $text-primary;
}

td.amount {
  font-weight: $font-weight-medium;
  color: $primary;
}

.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: $border-radius-md;
  font-size: 12px;
  font-weight: $font-weight-medium;
}

.status-pending {
  background-color: #e0e7ff;
  color: #1e40af;
}

.status-approved {
  background-color: #dcfce7;
  color: #166534;
}

.status-rejected {
  background-color: #fee2e2;
  color: #b91c1c;
}

.status-paid {
  background-color: #d1fae5;
  color: #047857;
}

.tx-hash {
  color: $info;
  text-decoration: none;
  font-family: $font-family-mono;

  &:hover {
    text-decoration: underline;
  }
}

// 分页
.pagination {
  display: flex;
  justify-content: center;
  gap: 5px;
  margin-top: 20px;
}

.page-link {
  display: inline-block;
  padding: 6px 12px;
  background-color: white;
  border: 1px solid $gray-300;
  color: $text-primary;
  text-decoration: none;
  border-radius: $border-radius-md;
  transition: all 0.2s;

  &:hover:not(.disabled, .active) {
    border-color: $primary;
    color: $primary;
  }

  &.active {
    background-color: $primary;
    color: white;
    border-color: $primary;
  }

  &.disabled {
    color: $gray-400;
    cursor: not-allowed;
  }
}

// 模态框样式
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: $z-index-modal;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: $z-index-modal-backdrop;
}

.modal-container {
  background-color: white;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  z-index: $z-index-modal;
  box-shadow: $shadow-lg;
  animation: modal-appear 0.3s ease-out;
}

@keyframes modal-appear {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid $gray-200;

  h3 {
    margin: 0;
    color: $text-primary;
    font-size: 18px;
    font-weight: $font-weight-semibold;
  }

  .btn-close {
    background-color: transparent;
    border: none;
    font-size: 18px;
    color: $gray-500;
    cursor: pointer;

    &:hover {
      color: $primary;
    }
  }
}

.modal-body {
  padding: 20px;
}

// 表单样式
.withdrawal-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  font-size: 14px;
  color: $text-secondary;
  font-weight: $font-weight-medium;
}

.form-control {
  padding: 10px 12px;
  border: 1px solid $gray-300;
  border-radius: $border-radius-md;
  font-size: 16px;
  color: $text-primary;
  width: 100%;
  transition: border-color 0.2s;

  &:focus {
    border-color: $primary;
    outline: none;
  }

  &.is-invalid {
    border-color: $danger;
  }

  &:disabled, &[readonly] {
    background-color: $gray-100;
    opacity: 0.8;
  }
}

textarea.form-control {
  resize: vertical;
  min-height: 80px;
}

.input-wrapper {
  position: relative;
}

.input-hint {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: $success;
}

.invalid-feedback {
  font-size: 12px;
  color: $danger;
}

.text-counter {
  font-size: 12px;
  color: $text-tertiary;
  text-align: right;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 8px;
}

.btn-primary {
  background-color: $primary;
  color: white;
  border: none;
  padding: 10px 24px;
  border-radius: $border-radius-md;
  font-size: 16px;
  font-weight: $font-weight-medium;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover:not(:disabled) {
    background-color: $primary-dark;
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

.btn-secondary {
  background-color: white;
  color: $text-primary;
  border: 1px solid $gray-300;
  padding: 10px 24px;
  border-radius: $border-radius-md;
  font-size: 16px;
  font-weight: $font-weight-medium;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    border-color: $primary;
    color: $primary;
  }
}

@media (max-width: $breakpoint-md) {
  .tab-item {
    padding: 12px 16px;
    font-size: 14px;
  }

  .overview-cards {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }

  .filter-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .date-range {
    flex-wrap: wrap;
  }

  .date-input {
    width: 120px;
  }
}

/* 经销商提现审核相关样式 */
.filter-section {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 20px;
}

.search-box {
  position: relative;
  flex: 1;
  min-width: 200px;
}

.search-input {
  width: 100%;
  padding: 10px 40px 10px 12px;
  border: 1px solid $gray-300;
  border-radius: $border-radius-md;
  font-size: 14px;
  outline: none;

  &:focus {
    border-color: $primary;
  }
}

.search-btn {
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  width: 40px;
  background: transparent;
  border: none;
  color: $gray-500;
  cursor: pointer;

  &:hover {
    color: $primary;
  }
}

.filter-item {
  display: flex;
  align-items: center;
}

.alert-card {
  display: flex;
  align-items: center;
  background-color: rgba($warning, 0.1);
  border-left: 4px solid $warning;
  border-radius: $border-radius-md;
  padding: 16px;
  margin-bottom: 20px;
}

.alert-icon {
  font-size: 24px;
  color: $warning;
  margin-right: 16px;
}

.alert-content {
  flex: 1;
}

.alert-title {
  font-weight: $font-weight-medium;
  font-size: 16px;
  color: $text-primary;
  margin-bottom: 4px;
}

.alert-desc {
  font-size: 14px;
  color: $text-secondary;
}

.btn-review-all {
  background-color: $warning;
  color: white;
  border: none;
  border-radius: $border-radius-md;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;

  i {
    margin-left: 8px;
  }

  &:hover {
    background-color: darken($warning, 10%);
  }
}

.distributor-cell {
  display: flex;
  align-items: center;
}

.distributor-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.distributor-detail {
  display: flex;
  align-items: center;

  .distributor-avatar {
    width: 40px;
    height: 40px;
    margin-right: 12px;
  }
}

.actions-cell {
  display: flex;
  gap: 8px;
}

.btn-action {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;

  &.view {
    background-color: $gray-100;
    color: $text-secondary;

    &:hover {
      background-color: $gray-200;
      color: $text-primary;
    }
  }

  &.approve {
    background-color: rgba($success, 0.1);
    color: $success;

    &:hover {
      background-color: $success;
      color: white;
    }
  }

  &.reject {
    background-color: rgba($danger, 0.1);
    color: $danger;

    &:hover {
      background-color: $danger;
      color: white;
    }
  }
}

.no-data {
  text-align: center;
  padding: 30px 0;
  color: $text-tertiary;
  font-style: italic;
}

/* 审核模态框相关样式 */
.review-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.review-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.review-label {
  font-size: 14px;
  color: $text-secondary;
  font-weight: $font-weight-medium;
}

.review-value {
  font-size: 16px;
  color: $text-primary;

  &.amount {
    font-weight: $font-weight-semibold;
    color: $primary;
  }

  &.address {
    font-family: $font-family-mono;
    font-size: 14px;
    word-break: break-all;
  }
}

.review-options {
  display: flex;
  gap: 16px;
}

.review-option {
  flex: 1;
  border: 1px solid $gray-300;
  border-radius: $border-radius-md;
  padding: 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;

  i {
    margin-right: 8px;
  }

  &.active {
    border-color: transparent;

    &:first-child {
      background-color: rgba($success, 0.1);
      color: $success;
    }

    &:last-child {
      background-color: rgba($danger, 0.1);
      color: $danger;
    }
  }

  &:hover:not(.active) {
    border-color: $primary;
  }
}
</style>
